package test.gps;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.TextItem;
import com.baidu.mapapi.map.TextOverlay;
import com.baidu.mapapi.map.Symbol.Color;
import com.baidu.mapapi.utils.CoordinateConvert;
import com.baidu.platform.comapi.basestruct.GeoPoint;
 
public class GPSMapActivity extends Activity{
	BMapManager mBMapMan = null;
	MapView mMapView = null;
	public TextView mBack;
	public TextView startTime;
	public TextView endTime;
	public TextView mProgressText;
	public TextView mWhere;
	public TextView mSelect;
	public Button mButton;
	public Spinner mSpinner;
	private FileHelper mHelper;
	String SATELLITESDATA = "卫星状态数据.txt";
	String GPSDATA = "实时定位数据.txt";
	String folderName="";
	MapController mMapController;
	int tnum=0;
	String [] satedata=new String[33];
	private ProgressBar mProgressBar = null; 
	int count=0;
        @Override
        public void onCreate(Bundle savedInstanceState){
        	super.onCreate(savedInstanceState);
        	mBMapMan=new BMapManager(getApplication());
        	mBMapMan.init("aXpcs8j9F4GEru03KlwlSFYB", null);  
        	//注意：请在试用setContentView前初始化BMapManager对象，否则会报错
        	setContentView(R.layout.map);
        	mMapView=(MapView)findViewById(R.id.bmapsView);
        	mProgressText = (TextView) findViewById(R.id.progressText);
        	mBack = (TextView) findViewById(R.id.mapback);
        	startTime = (TextView) findViewById(R.id.starttime);
        	endTime = (TextView) findViewById(R.id.endtime);
        	mWhere = (TextView) findViewById(R.id.where);
        	mSelect = (TextView) findViewById(R.id.select);
        	mButton = (Button) findViewById(R.id.buttonG);
        	mSpinner = (Spinner) findViewById(R.id.spinner1);
        	mHelper = new FileHelper(getApplicationContext());
        	mProgressBar = (ProgressBar)findViewById(R.id.progressBar1);  
        	Intent intent1 = getIntent();
    		 folderName = intent1.getStringExtra("foldername");
    		
        	mMapView.setBuiltInZoomControls(true);
        	//设置启用内置的缩放控件
        	 mMapController=mMapView.getController();
        	// 得到mMapView的控制权,可以用它控制和驱动平移和缩放
        	ProAT pro = new ProAT();
    		pro.execute();
    		mButton.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				if(tnum!=0){
    					String da=""+mSpinner.getSelectedItem();
    					da=da.substring(8);
    					Intent intent = new Intent(GPSMapActivity.this,
    							SatelliteDataActivity.class);
    					 intent.putExtra("satedata", satedata[Integer.parseInt(da)]);
    					 intent.putExtra("satenum", da);
    					startActivity(intent);
//    					Toast.makeText(
//    							GPSMapActivity.this,satedata[Integer.parseInt(da)], 10000).show();
    				}
    			}
    		});

    		mBack.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				finish();
    			}
    		});

        }
        
        public void addCustomElementsDemo(String []data){
        	GraphicsOverlay graphicsOverlay = new GraphicsOverlay(mMapView);
        	if(mMapView!=null&&graphicsOverlay!=null){
        		if(mMapView.getOverlays()!=null){
            mMapView.getOverlays().add(graphicsOverlay);
        	//添加折线
            graphicsOverlay.setData(drawLine(data));
          //添加点
            graphicsOverlay.setData(drawPoint(data[0]));
            graphicsOverlay.setData(drawPoint(data[count-1]));
        	}
        	}
        }
        /**
         * 绘制单点，该点状态不随地图状态变化而变化
         * @return 点对象
         */
        public Graphic drawPoint(String data){
        	
    	   	GeoPoint pt1 = gpsToBaidu(data);
    	   	
    	   	//构建点
      		Geometry pointGeometry = new Geometry();
      		//设置坐标
      		pointGeometry.setPoint(pt1, 10);
      		//设定样式
      		Symbol pointSymbol = new Symbol();
     		Symbol.Color pointColor = pointSymbol.new Color();
     		pointColor.red = 0;
     		pointColor.green = 126;
     		pointColor.blue = 255;
     		pointColor.alpha = 255;
     		pointSymbol.setPointSymbol(pointColor);
      		//生成Graphic对象
      		Graphic pointGraphic = new Graphic(pointGeometry, pointSymbol);
      		return pointGraphic;
        }
        /**
         * 绘制折线，该折线状态随地图状态变化
         * @return 折线对象
         */
        public Graphic drawLine(String []data){
    	  
    	    //构建线
      		Geometry lineGeometry = new Geometry();
      		//设定折线点坐标
      		GeoPoint[] linePoints = new GeoPoint[count];
      		for(int i=0;i<count;i++){
      			linePoints[i] = gpsToBaidu(data[i]);
      		}

      		lineGeometry.setPolyLine(linePoints);
      		//设定样式
      		Symbol lineSymbol = new Symbol();
      		Symbol.Color lineColor = lineSymbol.new Color();
      		lineColor.red = 33;
      		lineColor.green = 99;
      		lineColor.blue = 255;
      		lineColor.alpha = 255;
      		lineSymbol.setLineSymbol(lineColor, 10);
      		//生成Graphic对象
      		Graphic lineGraphic = new Graphic(lineGeometry, lineSymbol);
      		return lineGraphic;
        }
        public GeoPoint gpsToBaidu(String data){
        	String []p=data.split(",");
  			int lat = (int) (((int)(Float.valueOf(p[0])
					/ 100)+(100*(Float.valueOf(p[0])/100.0-(int)(Float.valueOf(p[0])/ 100))/60.0))*1E6);
    	   	int lon = (int) (((int)(Float.valueOf(p[1])
					/ 100)+(100*(Float.valueOf(p[1])/100.0-(int)(Float.valueOf(p[1])/ 100))/60.0))*1E6);   	
    	   	GeoPoint pt = new GeoPoint(lat, lon);
    	   	return CoordinateConvert.fromWgs84ToBaidu(pt);
        	
        	
        }
        @Override
        protected void onDestroy(){
                mMapView.destroy();
                if(mBMapMan!=null){
                        mBMapMan.destroy();
                        mBMapMan=null;
                }
                super.onDestroy();
        }
        @Override
        protected void onPause(){
                mMapView.onPause();
                if(mBMapMan!=null){
                       mBMapMan.stop();
                }
                super.onPause();
        }
        @Override
        protected void onResume(){
                mMapView.onResume();
                if(mBMapMan!=null){
                        mBMapMan.start();
                }
               super.onResume();
        }
    	public class ProAT extends AsyncTask<String, Integer, String> {
    		/*
    		 * 第一个参数为doInBackground传入的参数，
    		 * 第二个参数为onProgressUpdate传入参数,由doInBackground内调用publishProgress
    		 * (Interger)传值; 第三个为doInBackground返回值和onPostExecute传入的参数。
    		 */
    		String text = "数据加载完成";
    		String st;
    		String et;
    		String num="";
    		GeoPoint point;
    		
    		int l=20;
    		@Override
    		protected void onPreExecute() {
    			// 该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作，如在界面上转菊花提示
    			System.out.println("onPreExecute--->Task start");
    			super.onPreExecute();
    			mProgressText.setText("数据加载中...");  
    		}

    		@Override
    		protected String doInBackground(String... params) {
    			// 将在onPreExecute 方法执行后马上执行，该方法运行在后台线程中。
    			// 这里将主要负责执行那些很耗时的后台计算工作。
    			System.out.println("doInBackground---->");
    			String snrData =mHelper.readSDFile(folderName,SATELLITESDATA);
    			String [] snrItem=snrData.split("#\n");
    			for(int i=0;i<snrItem.length;i++){
    				String [] snrta=snrItem[i].split("\n");
    				String []isOK=snrta[snrta.length-1].split(",");
    				if(isOK[0].equals("A")){
    				for(int j=0;j<snrta.length-1;j++){
    					String [] snrtanum=snrta[j].split(",");
    					for(int k=1;k<33;k++){
    						if(Integer.parseInt(snrtanum[0])==k){
    							if(satedata[k] != null){
    								satedata[k]+=snrta[snrta.length-1]+","+snrtanum[1]+","+snrtanum[2]+","+snrtanum[3]+"#";
    							}else {
    								satedata[k]=snrta[snrta.length-1]+","+snrtanum[1]+","+snrtanum[2]+","+snrtanum[3]+"#";
								}
    							break;
    						}
    					}
    				}
    			}
    			}
    			for(int l=1;l<33;l++){
					if(satedata[l] != null){
						num+="卫星PRN码编号"+l+","	;
					}
    			}
    			String gpsData =mHelper.readSDFile(folderName,GPSDATA);
            	String [] gpsItem=gpsData.split("\n");
            	String []time=new String[gpsItem.length];
            	String []location=new String[gpsItem.length];
            	count =0;
            	for(int i=0,j=0;i<gpsItem.length;i++){
            		String []data=gpsItem[i].split(",");            		
            		if(data[0].equals("A")){
            			time[j]=data[2];
            			location[j]=data[4]+","+data[6];
            			j++;
            			count++;
            		}
            	}
            	if(count<5){
            		text="未能有效定位，无有效数据";
            		st ="开始时间：无有效数据";
            		et ="结束时间：无有效数据";
            		l=10;
            	      double cLat = 39.945 ;
            	      double cLon = 116.404 ;
            	      point = new GeoPoint((int)(cLat * 1E6), (int)(cLon * 1E6));
            	
            	}else{
            	 st ="开始时间："+folderName.substring(0,8)+","+((Integer.parseInt(time[0].substring(0,2))+8)%24)
            			+":"+time[0].substring(2,4)+":"+time[0].substring(4,6);
            	 et ="结束时间："+folderName.substring(0,8)+","+((Integer.parseInt(time[count-1].substring(0,2))+8)%24)
            			+":"+time[count-1].substring(2,4)+":"+time[count-1].substring(4,6);
            	
            	
            	 point = gpsToBaidu(location[0]);
            	//用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
            	
            	addCustomElementsDemo(location);

            	}

    			return "doInBackground";
    		}

    		@Override
    		protected void onProgressUpdate(Integer... values) {
    			System.out.println("更新进度" + values[0]);
    			// 在publishProgress方法被调用后，UI
    			// thread将调用这个方法从而在界面上展示任务的进展情况，例如通过一个进度条进行展示。
    			super.onProgressUpdate(values);
    		}

    		@Override
    		protected void onPostExecute(String result) {
    			// 在doInBackground 执行完成后，onPostExecute 方法将被UI
    			// thread调用，后台的计算结果将通过该方法传递到UI thread
    			// 用于更新UI
    			System.out.println("onPostExecute----->" + result);
    			super.onPostExecute(result);
            	//执行地图刷新使生效
                mMapView.refresh();
    			mProgressText.setText(text);  
    			startTime.setText(st);
            	endTime.setText(et);

        		mMapController.setCenter(point);//设置地图中心点
            	mMapController.setZoom(l);//设置地图zoom级别
    			try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			mProgressText.setVisibility(View.GONE);
    			mProgressBar.setVisibility(View.GONE);
    			String []m=num.split(",");
    			if(count<5){
    				tnum=0;
    			}else{ 			
    				tnum=m.length;
    			ArrayAdapter<String> adapter=new ArrayAdapter<String>(GPSMapActivity.this, android.R.layout.simple_spinner_item, m);
    			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    			mSpinner.setAdapter(adapter);
    			}
    			mSelect.setText("选择卫星编号查看详细数据(共"+tnum+"颗)");
    			
    			
    		}

    		@Override
    		protected void onCancelled() {
    			// 当用户取消操作时.
    			super.onCancelled();
    		}
    	}
} 

